package com.example.management.service.impl;

import com.example.management.mapper.DormitoryMapper;
import com.example.management.mapper.StudentMapper;
import com.example.management.pojo.Dormitory;
import com.example.management.pojo.Student;
import com.example.management.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public List<Student> getAllStudent() {

        return studentMapper.getAllStudent();
    }

    @Override
    public Student getStudent(Long number) {
        try {
            return studentMapper.selectByNumber(number);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Student> getSomeStudent(String buildingTag, String tag) {
        Dormitory dormitory = new Dormitory();
        dormitory.setBuildingTag(buildingTag);
        dormitory.setTag(tag);
        //        获取宿舍的人数并修改，弊端是：只有查询该宿舍的学生时才有效
        dormitory.setPeople(studentMapper.selectByDormitoryNum(dormitoryMapper.selectByAllTag(dormitory)).size());
        dormitoryMapper.changeDormitory(dormitory);
        try {
            return studentMapper.selectByDormitoryNum(dormitoryMapper.selectByAllTag(dormitory));
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Student> getStudentByMajorAndClass(String major, Integer classes) {
        Student student = new Student();
        student.setMajor(major);
        student.setClasses(classes);
        try {
            return studentMapper.selectByMajorAndClasses(student);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public String deleteStudent(Student student) {
        try {
            if (studentMapper.selectByNumber(student.getNumber()) != null) {
                studentMapper.deleteStudent(student.getNumber());
                return "删除成功！";
            } else {
                return "查无此学号";
            }
        } catch (Exception e) {
            return "删除失败!";
        }
    }

    @Override
    public String addStudent(Student student) {
        try {
            if (studentMapper.selectByNumber(student.getNumber()) == null) {
                studentMapper.addStudent(student);
                return "添加成功!   学号为" + student.getNumber();
            } else {
                return "这个学号已经被注册!";
            }
        } catch (Exception e) {
            return "添加失败！";
        }
    }


}
